import random
import logging
from io import BytesIO
from captcha.image import ImageCaptcha

from utils.myredis import r

logger = logging.getLogger(__name__)

def random_code(key=4):
    try:
        # a-z的范围字符
        str_a_z = [chr(num) for num in range(97, 122)]
        # A-Z的范围字符
        str_A_Z = [chr(num) for num in range(65, 90)]
        # 0-9的数字
        num_0_9 = [str(num) for num in range(0, 10)]
        # 随机抽样并返回为字符串
        return ''.join(random.sample(str_a_z + str_A_Z + num_0_9, key))
    except Exception as e:
        logger.error(f"生成随机验证码失败: {str(e)}")
        return None

def make_varify_image(code_str, image_uuid=None):
    try:
        if not code_str:
            logger.error("验证码字符串为空")
            return None
            
        # 生成图片验证码
        image = ImageCaptcha(width=120, height=40, fonts=['arial.ttf'])
        # 先生成图片数据
        image_data = image.generate(code_str)
        # 转换为图片对象
        image_obj = image.generate_image(code_str)
        
        # 把Image对象写入到IO流中
        out = BytesIO()
        # 使用更高质量的设置保存JPEG
        image_obj.save(out, format='JPEG', quality=95, optimize=True)
        out.seek(0)
        
        # 记录日志
        logger.info(f"验证码生成成功: {code_str}")
        
        # 返回图片内容
        return out.getvalue()
    except Exception as e:
        logger.error(f"生成验证码图片失败: {str(e)}")
        return None






